package com.augurit.common.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;


/**
 * 检查用户Session判断用户是否已登录
 */
public class SessionCheckFilter implements Filter {

	protected FilterConfig filterConfig;

	/**
	 * URL过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		HttpSession session = httpServletRequest.getSession();
		
		try {
			// 获取当前登录��ȡSession�е��û�����用户Session
			LoginUserForm loginUser = (LoginUserForm) session.getAttribute(WebContextUtils.SES_LOGIN_USER);
			
			// 登录系统
			if(httpServletRequest.getServletPath().equals("/")
					|| httpServletRequest.getServletPath().equals("/auth/login.action")
					|| httpServletRequest.getServletPath().equals("/auth/login!checkValid.action")
					|| httpServletRequest.getServletPath().equals("/config/init-config.action")
					|| httpServletRequest.getServletPath().equals("/config/init-config!init.action")){
					
				//允许继续执行
				chain.doFilter(request, response);
			}
			// 访问URL
			else{
				//非法访问，重定位登录页面
				if(loginUser == null){
					httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/auth/login.action");
				}
				//正常访问，允许继续执行
				else{
					chain.doFilter(request, response);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init(FilterConfig config) throws ServletException {
		this.filterConfig = config;
	}
	
	public void setFilterConfig(final FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
		this.filterConfig = null;
	}
}
